package com.byx.chatserver.service.impl;

import com.byx.chatserver.entity.FileType;
import com.byx.chatserver.service.IFileService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;
import java.util.Objects;

/**
 * FileServiceImpl
 *
 * @author Superb
 * @date 2021/4/6 9:40
 */
@Service
public class FileServiceImpl implements IFileService {
    private static final String REMOTE_URL = "https://www.byx0.tk:7001/chat/files/";
    // 后面接用户登录id/文件夹类型，如10000/image/
    private static final String LOCAL_URL = "/home/superb/ChatAppFiles/";

    @Override
    public String saveFile(MultipartFile file, String userId, FileType type) {
        if (file == null || file.isEmpty()){
            return null;
        }
        String fileName = null;
        try {
            fileName = URLDecoder.decode(Objects.requireNonNull(file.getOriginalFilename()),"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        assert fileName != null;

        String root = LOCAL_URL + userId + "/" + type.getName();
        File dest = new File(root, fileName);
        if (!dest.getParentFile().exists()){
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        }catch (Exception e){
            e.printStackTrace();
        }
        return dest.getAbsolutePath().replace(LOCAL_URL,REMOTE_URL);
    }

    @Override
    public String saveFiles(List<MultipartFile> fileList, String userId, FileType type) {
        for(MultipartFile file : fileList){

        }
        return null;
    }
}
